package com.example.mode.fragment;

import android.media.MediaPlayer;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.mode.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MusicFragment extends Fragment implements View.OnClickListener {

    private ImageView disc, discB, pre, next, play;
    private Button shunxu, suiji, only;
    private TextView title, author;
    private boolean flag = false;
    private MediaPlayer mediaPlayer;

    private OkHttpClient client = new OkHttpClient();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_music, container, false);
        disc = view.findViewById(R.id.disc);
        discB = view.findViewById(R.id.disc_c);
        pre = view.findViewById(R.id.playing_pre);
        next = view.findViewById(R.id.playing_next);
        play = view.findViewById(R.id.playing_play);
        title = view.findViewById(R.id.title);
        author = view.findViewById(R.id.action);
        shunxu = view.findViewById(R.id.shunxu);
        suiji = view.findViewById(R.id.suiji);
        only = view.findViewById(R.id.only);

        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.img_rotate);
        LinearInterpolator lin = new LinearInterpolator();
        discB.startAnimation(animation);

        fetchMusicData();

        play.setOnClickListener(this);
        next.setOnClickListener(this);
        pre.setOnClickListener(this);
        shunxu.setOnClickListener(this);
        suiji.setOnClickListener(this);
        only.setOnClickListener(this);

        return view;
    }

    private void fetchMusicData() {
        String url = "http://api.uomg.com/api/rand.music?sort=热歌榜&format=json";

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(() ->
                        Toast.makeText(getContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String jsonData = response.body().string();
                        JSONObject jsonObject = new JSONObject(jsonData);

                        int code = jsonObject.getInt("code");
                        if (code != 1) {
                            throw new JSONException("API返回错误状态码: " + code);
                        }

                        JSONObject data = jsonObject.getJSONObject("data");
                        String musicUrl = data.getString("url");
                        String musicName = data.getString("name");
                        String artist = data.getString("artistsname");
                        String picUrl = data.getString("picurl");

                        getActivity().runOnUiThread(() -> {
                            title.setText(musicName);
                            author.setText(artist);
                            Glide.with(getContext()).load(picUrl).into(disc);
                            prepareMediaPlayer(musicUrl);
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                        getActivity().runOnUiThread(() ->
                                Toast.makeText(getContext(), "数据解析错误: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                } else {
                    getActivity().runOnUiThread(() ->
                            Toast.makeText(getContext(), "请求失败，状态码: " + response.code(), Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void prepareMediaPlayer(String musicUrl) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }

        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(musicUrl);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(mp -> {
                if (flag) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                getActivity().runOnUiThread(() ->
                        Toast.makeText(getContext(), "播放错误: " + what, Toast.LENGTH_SHORT).show());
                return true;
            });
        } catch (IOException e) {
            e.printStackTrace();
            getActivity().runOnUiThread(() ->
                    Toast.makeText(getContext(), "音乐播放准备失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playing_pre:
            case R.id.playing_next:
            case R.id.suiji:
                fetchMusicData();
                break;

            case R.id.playing_play:
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        play.setImageResource(R.drawable.pause);
                        flag = false;
                    } else {
                        mediaPlayer.start();
                        play.setImageResource(R.drawable.play);
                        flag = true;
                    }
                }
                break;

            case R.id.shunxu:
                Toast.makeText(getContext(), "当前API不支持顺序播放", Toast.LENGTH_SHORT).show();
                break;

            case R.id.only:
                if (mediaPlayer != null) {
                    mediaPlayer.setLooping(!mediaPlayer.isLooping());
                    String msg = mediaPlayer.isLooping() ? "单曲循环已开启" : "单曲循环已关闭";
                    Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}